//
//  SearchExpressViewController.m
//  TengyunStation
//
//  Created by Johnny on 15/8/31.
//  Copyright (c) 2015年 xingrong. All rights reserved.
//

#import "SearchExpressViewController.h"
#import "SingleScanViewController.h"
#import "SocketRequest.h"
#import "Singleton.h"
#import "ExpressCompany.h"
#import "SearchExpressCell.h"
#import "ExpressDetailViewController.h"

@interface SearchExpressViewController ()<SocketRequestDelegate,SingleScanViewControllerDelegate,ExpressDetailViewControllerDelegate> {
    SocketRequest *_socketRequest;
    int _positionPage;
    NSString *_expressCompanyId;
    NSString *_expressType;
}

@end

@implementation SearchExpressViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"快件查询";
        _socketRequest = [[SocketRequest alloc] initWithSocketRequestDelegate:self];
        _searchExpressList = [NSMutableArray arrayWithCapacity:1];
        _positionPage = 1;
        _expressCompanyId = @"";
        _expressType = @"00";
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.tableView makeTip:@"请输入查询条件"];
    _dropMenuView.userInteractionEnabled = NO;
    [self getExpressCompanyListFromSqlite];
    [self handelNetWorkMethod];
}

- (void)getExpressCompanyListFromSqlite {
    NSArray *array = [ExpressCompany findAll];
    [Singleton shareInstance].expressCompanyList = array;
    [self getExpressCompanyListSocket];
}

- (void)getExpressCompanyListSocket {
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STR7"]];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    [_socketRequest addSocketData:mutableData SocketTag:1];
}

- (void)endRefresh {
    [self.tableView endRefreshPullTableView];
    [DSToast showText:@"查询条件不能为空" InView:self.tableView];
}

- (void)searchExpressSocket {
    if (_customSearch.searchTextField.text.length <= 0) {
        [ToastActivity dismissInView:self.view];
        [self performSelector:@selector(endRefresh) withObject:nil afterDelay:0.1];
        return;
    }
    if (_searchExpressList.count <= 0) {
        [self.tableView makeLoading];
    } else {
        self.tableView.backgroundView = nil;
    }
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STR5"]];
    [mutableData appendBytes:[SocketMethod checkLegal:_customSearch.searchTextField.text] length:64];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    [mutableData appendBytes:[SocketMethod checkLegal:_expressCompanyId] length:64];
    [mutableData appendBytes:[SocketMethod checkLegal:_expressType] length:8];
    NSString *page = [NSString stringWithFormat:@"%d",_positionPage];
    [mutableData appendBytes:[page UTF8String] length:16];
    [mutableData appendBytes:[@"10" UTF8String] length:16];
    [_socketRequest addSocketData:mutableData SocketTag:2];
}

#pragma mark UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _searchExpressList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 206;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIndentifier = @"SearchExpressCell";
    SearchExpressCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"SearchExpressCell" owner:self options:nil] lastObject];
    }
    SearchExpress *express = [_searchExpressList objectAtIndex:indexPath.row];
    [cell reloadSearchExpressCell:express];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    SearchExpress *express = [_searchExpressList objectAtIndex:indexPath.row];
    ExpressDetailViewController *expressDVC = [[ExpressDetailViewController alloc] initWithNibName:@"ExpressDetailViewController" bundle:nil];
    expressDVC.inwayExpressId = express.inwayExpressId;
    expressDVC.delegate = self;
    expressDVC.indexPath = indexPath;
    [self.navigationController pushViewController:expressDVC animated:YES];
}

#pragma mark ExpressDetailViewControllerDelegate
- (void)smsSendSuccess:(NSIndexPath *)indexPath {
    SearchExpress *express = [_searchExpressList objectAtIndex:indexPath.row];
    express.smsType = 0;
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (void)takeExpressSuccess:(NSIndexPath *)indexPath {
    SearchExpress *express = [_searchExpressList objectAtIndex:indexPath.row];
    express.expressType = @"0033";
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (void)updateExpress:(NSIndexPath *)indexPath Telephone:(NSString *)telephone Address:(NSString *)address {
    SearchExpress *express = [_searchExpressList objectAtIndex:indexPath.row];
    express.telephone = telephone;
    express.address = address;
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (void)updateExpress:(NSIndexPath *)indexPath Telephone:(NSString *)telephone Address:(NSString *)address Position:(NSString *)position {
    SearchExpress *express = [_searchExpressList objectAtIndex:indexPath.row];
    express.expressType = @"0006";
    express.smsType = 0;
    express.telephone = telephone;
    express.address = address;
    express.positon = position;
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

#pragma mark UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.tableView pullScrollViewDidScroll:scrollView];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self.tableView pullscrollViewDidEndDragging:scrollView];
}

#pragma mark PullTableViewDelegate
- (void)startRefreshHeaderView {
    _positionPage = 1;
    [self searchExpressSocket];
}

- (void)startRefreshFooterView {
    _positionPage += 10;
    [self searchExpressSocket];
}

#pragma mark CustomSearchViewDelegate
- (void)cancelSearch {
    _customSearch.isShowCancel = NO;
}

- (void)startScanning {
    SingleScanViewController *scanVC = [[SingleScanViewController alloc] initWithNibName:@"SingleScanViewController" bundle:nil];
    scanVC.delegate = self;
    [self.navigationController pushViewController:scanVC animated:YES];
}

- (void)startSearchText:(NSString *)text {
    if (_searchExpressList.count > 0) {
        [ToastActivity makeActivity:@"加载中..." InView:self.view];
    }
    self.tableView.contentOffset = CGPointMake(0, 0);
    _positionPage = 1;
    _dropMenuView.userInteractionEnabled = NO;
    _expressCompanyId = @"";
    _expressType = @"00";
    _customSearch.isShowCancel = NO;
    [self searchExpressSocket];
}

#pragma mark SingleScanViewControllerDelegate
- (void)didFinishSingleScanningCode:(NSString *)code {
    if (_searchExpressList.count > 0) {
        [ToastActivity makeActivity:@"加载中..." InView:self.view];
    }
    self.tableView.contentOffset = CGPointMake(0, 0);
    _positionPage = 1;
    _dropMenuView.userInteractionEnabled = NO;
    _expressCompanyId = @"";
    _expressType = @"00";
    _customSearch.searchTextField.text = code;
    [self searchExpressSocket];
}

#pragma mark DropMenuViewDelegate
- (void)didFinishExpressCompanyId:(NSString *)companyId {
    if (_searchExpressList.count > 0) {
        [ToastActivity makeActivity:@"加载中..." InView:self.view];
    }
    self.tableView.contentOffset = CGPointMake(0, 0);
    _expressCompanyId = companyId;
    _positionPage = 1;
    [self searchExpressSocket];
}

- (void)didFinishExpressType:(NSString *)expressType {
    if (_searchExpressList.count > 0) {
        [ToastActivity makeActivity:@"加载中..." InView:self.view];
    }
    self.tableView.contentOffset = CGPointMake(0, 0);
    _expressType = expressType;
    _positionPage = 1;
    [self searchExpressSocket];
}

#pragma mark SocketRequestDelegate
- (void)socket:(GCDAsyncSocket *)socket Code:(NSString *)code Msg:(NSString *)msg Data:(NSData *)data {
    [self.tableView endRefreshPullTableView];
    [ToastActivity dismissInView:self.view];
    if ([code isEqualToString:SuccessSocket]) {
        if (socket.socketTag == 1) {
            [ExpressCompany clearTable];
            NSString *content = [SocketMethod stringDecryHexData:data];
            DLog(@"ExpressCompany:%@",content);
            NSArray *array = [content componentsSeparatedByString:@"|"];
            NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:1];
            for (NSString *string in array) {
                if (string.length > 0) {
                    ExpressCompany *company = [[ExpressCompany alloc] initWithString:string];
                    [company saveOrUpdate];
                    [mutableArray addObject:company];
                }
            }
            [Singleton shareInstance].expressCompanyList = mutableArray;
        } else if (socket.socketTag == 2) {
            if (_positionPage == 1) {
                [_searchExpressList removeAllObjects];
            }
            NSString *content = [SocketMethod stringDecryHexData:data];
            DLog(@"content:%@",content);
            NSArray *array = [content componentsSeparatedByString:@"|"];
            NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:1];
            for (NSString *string in array) {
                if (string.length > 0) {
                    SearchExpress *express = [[SearchExpress alloc] initWithString:string];
                    [mutableArray addObject:express];
                }
            }
            [_searchExpressList addObjectsFromArray:mutableArray];
            self.tableView.isShowFooterView = ((mutableArray.count < 10) ? NO : YES);
            if (_searchExpressList.count <= 0) {
                [self.tableView makeTip:@"查无结果。请重新搜索！"];
            } else {
                _dropMenuView.userInteractionEnabled = YES;
                self.tableView.backgroundView = nil;
            }
            [self.tableView reloadData];
        }
    } else {
        if (_searchExpressList.count <= 0) {
            [self.tableView makeTip:msg];
        } else {
            [DSToast showText:msg InView:self.view];
        }
    }
}

- (void)socket:(GCDAsyncSocket *)socket Msg:(NSString *)msg {
    [self.tableView endRefreshPullTableView];
    [ToastActivity dismissInView:self.view];
    if (_searchExpressList.count <= 0) {
        [self.tableView makeTip:msg Title:@"重新加载" Target:self Selector:@selector(searchExpressSocket)];
    }
    [DSToast showText:msg InView:self.view];
}

- (void)dealloc {
    _socketRequest = nil;
    _searchExpressList = nil;
}

@end
